package graphql

func EndpointAvgLatency(serviceName string, endpointName string, start string, end string) (map[int64]any, error) {
	var condition MetricsCondition
	var duration Duration
	if skywalkingVersion == SW9 {
		condition, duration = GetCondition(serviceName, endpointName, start, end, "endpoint_resp_time")
	} else {
		condition, duration = GetCondition(serviceName, endpointName, start, end, "endpoint_avg")
	}

	latencies, err := GetTimeSeriesMetric(condition, duration)
	return transformMillSecondToNanoSecond(latencies), err
}

func EndpointCps(serviceName string, endpointName string, start string, end string) (map[int64]any, error) {
	condition, duration := GetCondition(serviceName, endpointName, start, end, "endpoint_cpm")
	throughput, err := GetTimeSeriesMetric(condition, duration)
	return transformCpmToCps(throughput), err
}

var PercentilesLabels = map[string]string{
	"0": "0.5000000000",
	"1": "0.7500000000",
	"2": "0.9000000000",
	"3": "0.9500000000",
	"4": "0.9900000000",
}

func EndpointPercentiles(serviceName string, endpointName string, start string, end string) (map[string]map[int64]any, error) {
	condition, duration := GetCondition(serviceName, endpointName, start, end, "endpoint_percentile")
	percentiles, err := GetLabeledTimeSeriesMetric(condition, duration, []string{"0", "1", "2", "3", "4"})
	return percentiles, err
}

func transformCpmToCps(throughput map[int64]any) map[int64]any {
	for ts, cpm := range throughput {
		throughput[ts] = (float64)(cpm.(int64)) / float64(60)
	}
	return throughput
}

func transformMillSecondToNanoSecond(avgLatency map[int64]any) map[int64]any {
	for ts, cpm := range avgLatency {
		avgLatency[ts] = (float64)(cpm.(int64)) * 1e6
	}
	return avgLatency
}
